package org.niux.aims.dao.impl;

import java.util.List;
import java.util.logging.Level;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.niux.aims.dao.IApplicationDAO;
import org.niux.aims.models.Application;
import org.niux.aims.models.EntityManagerHelper;
import org.springframework.stereotype.Repository;

/**
 * 
 * Copyright (c) 2009,niux<br>
 * All rights reserved.<br>
 * 
 * 文件名称：ApplicationDAO.java<br>
 * 摘    要：应用数据操作类<br>
 * <br>
 * 当前版本：<br>
 * 作    者：铭显 Email: <a href="mailto:liangmingxian@gmail.com">liangmingxian@gmail.com</a><br>
 * 完成日期：@since 2013-7-30<br>
 * <br>
 * 取代版本：<br>
 * 原作者  ：<br>
 * 完成日期：@since Oct 22, 2009<br>
 */
@Repository(value="applicationDao")
public class ApplicationDAO implements IApplicationDAO {
	// property constants
	public static final String APP_NAME = "appName";

	private EntityManager getEntityManager() {
		return EntityManagerHelper.getEntityManager();
	}
	
	/**
	 * 
	 * 方法概述：保存应用数据
	 * 描述：保存应用数据
	 * @param entity
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-8-2
	 */
	public void save(Application entity) {
		try {
			EntityManagerHelper.beginTransaction();
			getEntityManager().persist(entity);
			EntityManagerHelper.commit();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：删除应用数据
	 * 描述：删除应用数据
	 * @param entity
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-8-6
	 */
	public void delete(Application entity) {
		try {
			EntityManagerHelper.beginTransaction();
			entity = getEntityManager().getReference(Application.class,entity.getId());
			getEntityManager().remove(entity);
			EntityManagerHelper.commit();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("delete failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：修改应用数据
	 * 描述：修改应用数据
	 * @param entity
	 * @return
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-8-6
	 */
	public Application update(Application entity) {
		try {
			EntityManagerHelper.beginTransaction();
			Application result = getEntityManager().merge(entity);
			EntityManagerHelper.commit();
			return result;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：根据ID获取应用数据
	 * 描述：根据ID获取应用数据
	 * @param id
	 * @return
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-8-6
	 */
	public Application findById(Integer id) {
		try {
			Application instance = getEntityManager().find(Application.class,
					id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * Find all Application entities with a specific property value.
	 * 
	 * @param propertyName
	 *            the name of the Application property to query
	 * @param value
	 *            the property value to match
	 * @param rowStartIdxAndCount
	 *            Optional int varargs. rowStartIdxAndCount[0] specifies the the
	 *            row index in the query result-set to begin collecting the
	 *            results. rowStartIdxAndCount[1] specifies the the maximum
	 *            number of results to return.
	 * @return List<Application> found by query
	 */
	@SuppressWarnings("unchecked")
	public List<Application> findByProperty(String propertyName,
			final Object value, final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding Application instance with property: "
				+ propertyName + ", value: " + value, Level.INFO, null);
		try {
			final String queryString = "select model from Application model where model."
					+ propertyName + "= :propertyValue";
			Query query = getEntityManager().createQuery(queryString);
			query.setParameter("propertyValue", value);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find by property name failed",
					Level.SEVERE, re);
			throw re;
		}
	}

	public List<Application> findByAppName(Object appName,
			int... rowStartIdxAndCount) {
		return findByProperty(APP_NAME, appName, rowStartIdxAndCount);
	}

	/**
	 * 
	 * 方法概述：获取所有应用数据
	 * 描述：获取所有应用数据
	 * @param rowStartIdxAndCount
	 * @return
	 * 返回类型：
	 * 修改人：梁铭显
	 * 修改时间：2013-8-15
	 */
	@SuppressWarnings("unchecked")
	public List<Application> findAll(final int... rowStartIdxAndCount) {
		EntityManagerHelper.log("finding all Application instances",
				Level.INFO, null);
		try {
			final String queryString = "select model from Application model";
			Query query = getEntityManager().createQuery(queryString);
			if (rowStartIdxAndCount != null && rowStartIdxAndCount.length > 0) {
				int rowStartIdx = Math.max(0, rowStartIdxAndCount[0]);
				if (rowStartIdx > 0) {
					query.setFirstResult(rowStartIdx);
				}

				if (rowStartIdxAndCount.length > 1) {
					int rowCount = Math.max(0, rowStartIdxAndCount[1]);
					if (rowCount > 0) {
						query.setMaxResults(rowCount);
					}
				}
			}
			return query.getResultList();
		} catch (RuntimeException re) {
			EntityManagerHelper.log("find all failed", Level.SEVERE, re);
			throw re;
		}
	}

	/**
	 * 
	 * 方法概述：分页获取应用数据
	 * 描述：分页获取应用数据
	 * @param startPage
	 * @param pageSize
	 * @return
	 * 返回类型：List<Application>
	 * 修改人：梁铭显
	 * 修改时间：2013-8-1
	 */
	@SuppressWarnings("unchecked")
	public List<Application> findByPage(int startPage, int pageSize){
		StringBuffer hql = new StringBuffer();
		
		hql.append("SELECT app ");
		hql.append("FROM Application app ");
		hql.append("WHERE 1=1 ");
		
		Query query = getEntityManager().createQuery(hql.toString());
		
		query.setFirstResult(startPage);
		query.setMaxResults(pageSize);
		
		List<Application> apps = query.getResultList();
		
		return apps;
	}
}